package sg.edu.ntu.bloch.tictactoe.datasource.player;

import java.security.InvalidParameterException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import sg.edu.ntu.bloch.tictactoe.engine.Player;

class PlayerMapSource implements PlayerSource {

	// playerMap contain the collection of Player index by their username
	private Map<String, Player> playerMap = null;

	public PlayerMapSource() {
		playerMap = new ConcurrentHashMap<String, Player>();
	}

	/*
	 * getPlayer will return the Player base on userName//TODO might need to
	 * Guard playerMap for thread safety
	 */
	@Override
	public Player getPlayer(String name) {
		if (name == null) {
			throw new InvalidParameterException("Player name cannot be null");
		} else {
			return playerMap.get(name);
		}
	}

	@Override
	public boolean newPlayer(Player player) {
		boolean success = false;
		if (player == null) {
			throw new InvalidParameterException("Player cannot be null");
		}
		assert player.getPlayer() != null;
		assert !player.getPlayer().trim().isEmpty();
		if (!playerMap.containsKey(player.getPlayer())) {
			playerMap.put(player.getPlayer(), player);
			success = true;
		}
		return success;
	}
	
	@Override
	public Set<String> getAllName() {
		assert playerMap != null;
		return playerMap.keySet();
	}
	
	@Override
	public boolean unqiueName(String name){
		assert playerMap != null;
		return playerMap.containsKey(name) == false;
	}

}
